package org.je.thread;

import org.je.util.WrappedBlockingQueue;

/**
 * @author fanyifeng
 */
public class SimplePool
{
	private TaskWorker[]				workers;
	private WrappedBlockingQueue<Task>	taskQueue;

	/**
	 * @param threadCount
	 */
	public SimplePool(int threadCount) {
		if (threadCount <= 0 || threadCount > 2000) {
			throw new IllegalArgumentException("thread count must >0 && <=2000");
		}
		taskQueue = new WrappedBlockingQueue<Task>(threadCount * 10);
		workers = new TaskWorker[threadCount];
		for (int i = 0; i < workers.length; ++i) {
			workers[i] = new TaskWorker(taskQueue);
		}
	}

	/**
	 * @param task
	 */
	public void submit(Task task) {
		if (task == null)
			throw new NullPointerException("task-is-null");
		startThreads();// 启动线程
		taskQueue.put(task);
	}

	public void close() {
		for (int i = 0; i < workers.length; ++i) {
			taskQueue.put(Task.CLOSE_THREAD);
		}
	}
	
	public int queueSize(){
		return taskQueue.size();
	}

	private volatile boolean	isStarted	= false;

	private void startThreads() {
		if (isStarted)
			return;
		synchronized (this) {
			if (isStarted)
				return;
			isStarted = true;
		}
		for (TaskWorker worker : workers) {
			worker.start();
		}
	}
}
